﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using System.Net.Sockets;
using System.Net;
using System.Collections;
using System.Threading;
using System.Text.RegularExpressions;

namespace ServerApp
{
    public class UDPServices
    {
        #region khoi tao 
        UdpClient sendingClient;
        #endregion

        String testIP;
        public void server_Load()
        {
            Thread listenThread = new Thread(new ThreadStart(tets));
            listenThread.Start();
            listenThread.IsBackground = true;

        }
        public String returnIP()
        {
            return testIP;
        }
        public void tets()
        {
            
            int recv;
            byte[] data = new byte[1024];
            IPEndPoint ipendp = new IPEndPoint(IPAddress.Any, 8080);
            Socket newsock = new Socket(AddressFamily.InterNetwork, SocketType.Dgram, ProtocolType.Udp);
            newsock.Bind(ipendp);
            MessageBox.Show("waiting for connection....");
            IPEndPoint sender = new IPEndPoint(IPAddress.Any, 8080);
            EndPoint tmpRemote = (EndPoint)(sender);
            //recv = newsock.ReceiveFrom(data, ref tmpRemote);
            //MessageBox.Show("data is : " + tmpRemote.ToString() + "and ---" + Encoding.ASCII.GetString(data, 0, recv));
            TCPservices tcpSv = new TCPservices();
            while (true)
            {
                data = new byte[1024];
               recv = newsock.ReceiveFrom(data, ref tmpRemote);
               string test = Encoding.ASCII.GetString(data);
             //  MessageBox.Show("data in while: " + test);
               testIP = test;
               string[] a = Regex.Split(test, "\0");
               tcpSv.respones(a[0]);
                
               // string dataToSend = Dns.GetHostName();
               // System.Text.ASCIIEncoding encoding = new System.Text.ASCIIEncoding();
               // byte[] byteToSend = encoding.GetBytes(dataToSend);
               // newsock.SendTo(byteToSend, byteToSend.Length, SocketFlags.None, tmpRemote);
               // newsock.SendTo(byteToSend, tmpRemote);
               //
                //tcpSv.respones(a[0], 8080, dataToSend);
               
              
            }
            newsock.Close();
        }
        

        
    }
}
